package com.hsogoo.collate.datasource;

import com.hsogoo.collate.domain.DataSourceConfig;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;

/**
 * @Author huangsaigang
 * Created @2019-10-27.
 */
public class DataSourceCreator {

    /**创建数据源*/
    public static DataSource createDataSource(DataSourceConfig dataSourceConfig){

        HikariConfig config = new HikariConfig();
        config.setDriverClassName(dataSourceConfig.getDriveName());
        config.setJdbcUrl(dataSourceConfig.getUrl()); //数据源
        config.setUsername(dataSourceConfig.getUsername()); //用户名
        config.setPassword(getPassword(dataSourceConfig.getPassword(), dataSourceConfig.isEncrypted())); //密码
        //以下也可以做为配置项,这里为了简化写死了
        config.addDataSourceProperty("cachePrepStmts", "true"); //是否自定义配置，为true时下面两个参数才生效
        config.addDataSourceProperty("prepStmtCacheSize", "250"); //连接池大小默认25，官方推荐250-500
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); //单条语句最大长度默认256，官方推荐2048
        config.addDataSourceProperty("useServerPrepStmts", "true"); //新版本MySQL支持服务器端准备，开启能够得到显著性能提升
        config.addDataSourceProperty("useLocalSessionState", "true");
        config.addDataSourceProperty("useLocalTransactionState", "true");
        config.addDataSourceProperty("rewriteBatchedStatements", "true");
        config.addDataSourceProperty("cacheResultSetMetadata", "true");
        config.addDataSourceProperty("cacheServerConfiguration", "true");
        config.addDataSourceProperty("elideSetAutoCommits", "true");
        config.addDataSourceProperty("maintainTimeStats", "false");

        return new HikariDataSource(config);
    }

    private static String getPassword(String password, boolean encrypted){
        if(encrypted){
            //TODO:解密算法
            return password;
        }
        return password;
    }
}
